package demo_0416.homework;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BankAccounts {
    private static final String DATA_FILE = "resource\\accounts.txt";
    private Map<Integer, BankAccount> accounts;
    public BankAccounts() {
        accounts = new HashMap<>();
        loadAccounts();
    }

    private void loadAccounts() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(DATA_FILE))) {
            accounts = (HashMap<Integer, BankAccount>) ois.readObject();
        } catch (FileNotFoundException e) {
            System.out.println("未找到数据文件，将创建新文件。");
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("加载数据时出错: " + e.getMessage());
        }
    }

    public void saveAccounts() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(DATA_FILE))) {
            oos.writeObject(accounts);
        } catch (IOException e) {
            System.out.println("保存数据时出错: " + e.getMessage());
        }
    }

    public boolean addAccount(BankAccount account) {
        if (accounts.containsKey(account.getId())) {
            return false;
        }
        accounts.put(account.getId(), account);
        return true;
    }

    public List<BankAccount> getAllAccounts() {
        return new ArrayList<>(accounts.values());
    }

    public BankAccount getAccount(int id) {
        return accounts.get(id);
    }

    public boolean updateAccount(BankAccount account) {
        if (!accounts.containsKey(account.getId())) {
            return false;
        }
        accounts.put(account.getId(), account);
        return true;
    }

    public boolean deleteAccount(int id) {
        return accounts.remove(id) != null;
    }

    public void exportPrintFile(String filename) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {

            writer.printf("%-5s %-15s %-15s %-10s%n", "ID", "First Name", "Last Name", "Balance");
            writer.println("--------------------------------------------");
            for (BankAccount bankAccount : getAllAccounts()) {
                System.out.printf("%-5s %-15s %-15s %-10s%n",bankAccount.getId(),bankAccount.getFirstName(),bankAccount.getLastName(),bankAccount.getBalance());
            }

        } catch (IOException e) {
            System.out.println("生成打印文件时出错: " + e.getMessage());
        }
    }
}
